package org.fujene.diskblock.local;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.fujene.constants.Constants;
import org.fujene.diskblock.DiskBlock;
import org.fujene.memoryblock.MemoryBlock;
import org.fujene.memoryblock.local.LocalContentBlock;
import org.fujene.toolbox.ByteConverter;

public class ContentDiskBlock extends DiskBlock{

	public ContentDiskBlock(File fileDesc) throws Exception{
		super(fileDesc);
	}

	public ContentDiskBlock(LocalContentBlock memBlock, String dir){
		super(memBlock, dir);
	}

	public ContentDiskBlock(int ID, File desc, int defaultBodySize, int defaultOptionSize) throws Exception{
		super(ID, desc, Constants.MEMORY_TYPE_CONTENTS, defaultBodySize, defaultOptionSize);
	}

	private String getBodyForContents(int from) throws IOException{
		if (from >= bodySize) return null;

		FileInputStream stream = null;
		byte[] val = new byte[STRLEN];
		try{
			stream = new FileInputStream(fileDesc);
			switch(version){
			case Constants.FINALVER:
				stream.skip((4 * HEADERLEN) + (4 * optionSize) + from);
				stream.read(val);
				int length = ByteConverter.byteToInt(val);
				val = new byte[length];
				stream.read(val);
				break;

			default:
				break;
			}
		}
		finally{
			if (stream != null) stream.close();
		}

		return new String(val, "UTF-8");
	}

	public String getContent(int ptr) throws Exception{
		return getBodyForContents(ptr);
	}

	public int getCount() throws Exception{
		return this.getOption(0);
	}

	@Override
	public int toMemory(MemoryBlock memBlock){
		if (memBlock instanceof LocalContentBlock){
			try{
				memBlock.setOption(0, this.getOption(0));
				memBlock.setBody(this.getBody(0, this.bodySize), 0);
				memBlock.setBodyVacancy(this.bodyVacancy);
			}
			catch(Exception e){}
		}
		return this.bodySize - this.bodyVacancy;
	}

	@Override
	public byte[] getData(){
		throw new NoSuchMethodError("Unimplemented method");
	}
}
